package com.atguigu.gmall.activity.controller;

import com.atguigu.gmall.activity.service.SeckillGoodsService;
import com.atguigu.gmall.activity.util.CacheHelper;
import com.atguigu.gmall.activity.util.DateUtil;
import com.atguigu.gmall.common.constant.MqConst;
import com.atguigu.gmall.common.constant.RedisConst;
import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.common.result.ResultCodeEnum;
import com.atguigu.gmall.common.service.RabbitService;
import com.atguigu.gmall.common.util.AuthContextHolder;
import com.atguigu.gmall.common.util.MD5;
import com.atguigu.gmall.model.activity.OrderRecode;
import com.atguigu.gmall.model.activity.SeckillGoods;
import com.atguigu.gmall.model.activity.UserRecode;
import com.atguigu.gmall.model.order.OrderDetail;
import com.atguigu.gmall.model.order.OrderInfo;
import org.redisson.misc.Hash;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.cache.CacheProperties;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.nio.channels.SelectionKey;
import java.util.*;

/**
 * 秒杀管理
 */
@RestController
@RequestMapping("/api/activity/seckill")
public class SeckillGoodsApiController {

    @Autowired
    private SeckillGoodsService seckillGoodsService;
    @Autowired
    private RabbitService rabbitService;
    @Autowired
    private RabbitTemplate rabbitTemplate;

    //回显秒杀频道首页 所有秒杀的商品
    @GetMapping("/findAll")
    public Result findAll() {
        List<SeckillGoods> seckillGoodsList = seckillGoodsService.findAll();
        return Result.ok(seckillGoodsList);
    }

    //根据SkuId查询一个秒杀商品
    @GetMapping("/getSeckillGoods/{skuId}")
    public Result getSeckillGoods(@PathVariable(name = "skuId") Long skuId) {
        SeckillGoods seckillGoods = seckillGoodsService.getSeckillGoods(skuId);
        return Result.ok(seckillGoods);
    }

    //获取下单码
    @GetMapping("/auth/getSeckillSkuIdStr/{skuId}")
    public Result getSeckillSkuIdStr(@PathVariable(name = "skuId") Long skuId
            , HttpServletRequest request) {
        String userId = AuthContextHolder.getUserId(request);
        //1:SkuId对应的商品是不是在活动范围 内
        SeckillGoods seckillGoods = seckillGoodsService.getSeckillGoods(skuId);
        if (seckillGoods != null) {
            //当前时间
            Date curDate = new Date();
            //开始时间
            //当前时间
            //结束时间
            //参数1： 小  参数2：大  返回值true
            if (DateUtil.dateCompare(seckillGoods.getStartTime(), curDate)
                    && DateUtil.dateCompare(curDate, seckillGoods.getEndTime())) {
                //在活动范围之内  下单码 允许立即抢购
                return Result.ok(MD5.encrypt(skuId + userId));
            }
            if (DateUtil.dateCompare(curDate, seckillGoods.getStartTime())) {
                return Result.fail().message("当前商品活动尚未开始");
            }
            if (DateUtil.dateCompare(seckillGoods.getEndTime(), curDate)) {
                return Result.fail().message("当前商品活动已经结束");
            }
        } else {
            return Result.fail().message("当前商品不存在");
        }
        return Result.ok();
    }

    //预下单   去抢购秒杀商品
    @PostMapping("/auth/seckillOrder/{skuId}")
    public Result seckillOrder(@PathVariable(name = "skuId") Long skuId, String skuIdStr
            , HttpServletRequest request) {
        String userId = AuthContextHolder.getUserId(request);
        //1:判断下单码是否正确
        if (StringUtils.isEmpty(skuIdStr)) {
            return Result.build(null, ResultCodeEnum.SECKILL_ILLEGAL);
        }

        if (skuIdStr.equals(MD5.encrypt(skuId + userId))) {
            //下单码是正确
            //状态位
            String state = (String) CacheHelper.get(skuId.toString());
            if (StringUtils.isEmpty(state) || "0".equals(state)) {
                return Result.build(null, ResultCodeEnum.SECKILL_FINISH);
            }
            //预下单
            UserRecode userRecode = new UserRecode();
            userRecode.setUserId(userId);
            userRecode.setSkuId(skuId);
            rabbitTemplate.convertAndSend(MqConst.EXCHANGE_DIRECT_SECKILL_USER,
                    MqConst.ROUTING_SECKILL_USER, userRecode);
        } else {
            //请求不合法
            return Result.build(null, ResultCodeEnum.SECKILL_ILLEGAL);
        }

        return Result.ok();
    }

    @Autowired
    private RedisTemplate redisTemplate;

    //轮循查询结果
    @GetMapping("/auth/checkOrder/{skuId}")
    public Result checkOrder(@PathVariable(name = "skuId") Long skuId, HttpServletRequest request) {
        String userId = AuthContextHolder.getUserId(request);
        //获取当前用户是否来抢购  //不存在是 true    存在是false  setnx
        Boolean isExist = redisTemplate.opsForValue().setIfAbsent(RedisConst.SECKILL_USER + userId, skuId);
        if (!isExist) {
            //用户已经从MQ中出来了  到底抢购成功了没呢？
            //1:抢购成功  我的订单
            Object o = redisTemplate.opsForValue().get(RedisConst.SECKILL_ORDERS_USERS + userId);
            if (null != o) {
                return Result.build(null, ResultCodeEnum.SECKILL_ORDER_SUCCESS);
            }
            //2:抢购成功 预下单
            Object o1 = redisTemplate.opsForValue().get(RedisConst.SECKILL_ORDERS + userId);
            if (null != o1) {
                return Result.build(null, ResultCodeEnum.SECKILL_SUCCESS);
            }
            //用户已经从MQ中出来了  并且  下好订单了吗 没有  有订单资格 也没有  抢单失败
            return Result.build(null, ResultCodeEnum.SECKILL_FAIL);
        }else{
            //用户还没有从MQ中出来了
            //正在排队中
            return Result.build(null, ResultCodeEnum.SECKILL_RUN);
        }
    }

    //查询秒杀商品 准备订单详情集合
    @GetMapping("getOrderDetail/{userId}")
    public Result getOrderDetail(@PathVariable(name = "userId") String userId){
        //1:从缓存中获取出下单资格
        OrderRecode orderRecode = (OrderRecode) redisTemplate.opsForValue().get(RedisConst.SECKILL_ORDERS + userId);
        //2:将秒杀商品信息转移到订单详情对象中
        SeckillGoods seckillGoods = orderRecode.getSeckillGoods();

        //商品清单  只有一款商品  秒杀商品  只有一件
        List<OrderDetail> detailArrayList = new ArrayList<>();
        OrderDetail orderDetail = new OrderDetail();
        orderDetail.setImgUrl(seckillGoods.getSkuDefaultImg());
        orderDetail.setOrderPrice(seckillGoods.getCostPrice());
        orderDetail.setSkuName(seckillGoods.getSkuName());
        orderDetail.setSkuNum(orderRecode.getNum());
        orderDetail.setSkuId(seckillGoods.getSkuId());
        detailArrayList.add(orderDetail);
        Map map = new HashMap<>();
        map.put("detailArrayList",detailArrayList);
        //总件数
        map.put("totalNum",orderRecode.getNum());
        //总金额
        map.put("totalAmount",orderDetail.getOrderPrice());
        return Result.ok(map);
    }

    //秒杀商品提交订单
    @PostMapping("/auth/submitOrder")
    public Result submitOrder(@RequestBody OrderInfo orderInfo,HttpServletRequest request){
        String userId = AuthContextHolder.getUserId(request);
        //1:保存订单  保存订单详情  Mysql
        //2:保存真订单  在缓存
        redisTemplate.opsForValue().set(RedisConst.SECKILL_ORDERS_USERS + userId,orderInfo);
        //3:删除预下单
        redisTemplate.delete(RedisConst.SECKILL_ORDERS + userId);
        return Result.ok();
    }

}
